.PHONY: all clean

include ${P_BASE}/global/utils/make/target
include ${P_BASE}/global/utils/make/local
include ${P_BASE}/global/utils/make/cmds
include ${P_BASE}/global/utils/make/escape

all: ${T_BASE}/mod_${MOD_NAME}

T_CC_MOD_FLAGS ?= 	${T_CC_GLOBAL_FLAGS} -gstabs ${T_CC_FLAG_INC}${P_BASE} ${T_CC_FLAG_INC}${P_BASE}/modules/${MOD_NAME} \
					${T_CC_FLAG_INC}${P_BASE}/modules/${MOD_NAME}/inc -nostdlib -nostdinc -fno-builtin

SRCFILES:= $(shell $(call C_FIND,.,'(' '!' -regex '\./_.*' ')' -and '(' -iname '*.c' -or -iname '*.S' ')') | $(call C_SED,-e 's!\./!!g'))
OBJFILES:= $(addprefix ${T_BASE}/mod_${MOD_NAME}_,\
		     $(addsuffix .o,$(call E_ENCODE,${SRCFILES})))
DEPFILES:= $(OBJFILES:.o=.d)

-include $(DEPFILES)

${T_BASE}/mod_${MOD_NAME}_%.S.d: 
	@$(call C_ECHO,DEP $(call E_DECODE,$*).S)
	${V}$(call T_CC, $(call E_DECODE,$*).S,$@,-D__ASSEMBLY__ -MM ${T_CC_MOD_FLAGS} -MT $(@:.d=.o))
	${V}$(call C_ECHO,"$(@:.d=.o): $(call E_DECODE,$*).S") >> $@

${T_BASE}/mod_${MOD_NAME}_%.c.d: 
	${V}$(call C_ECHO,DEP $(call E_DECODE,$*).c)
	${V}$(call T_CC, $(call E_DECODE,$*).c,$@,-MM ${T_CC_MOD_FLAGS} -MT $(@:.d=.o))
	${V}$(call C_ECHO,"$(@:.d=.o): $(call E_DECODE,$*).c") >> $@

${T_BASE}/mod_${MOD_NAME}_%.S.o: ${T_BASE}/mod_${MOD_NAME}_%.S.d
	@$(call C_ECHO,CC $(call E_DECODE,$*).S)
	${V}$(call T_CC,$(call E_DECODE,$*).S,$@,-D__ASSEMBLY__ ${T_CC_MOD_FLAGS} ${T_CC_FLAG_OBJ})

${T_BASE}/mod_${MOD_NAME}_%.c.o: ${T_BASE}/mod_${MOD_NAME}_%.c.d
	@$(call C_ECHO,CC $(call E_DECODE,$*).c)
	${V}$(call T_CC,$(call E_DECODE,$*).c,$@,${T_CC_MOD_FLAGS} ${T_CC_FLAG_OBJ})

${T_BASE}/mod_${MOD_NAME}_user_bfs.o: ${T_BASE}/mod_${MOD_NAME}_user
	${V}cd ${T_BASE}; $(call T_OBJCOPY,mod_${MOD_NAME}_user,mod_${MOD_NAME}_user_bfs.o,-I binary -O elf32-i386 -B i386)

${T_BASE}/mod_${MOD_NAME}: 	${OBJFILES} ${T_BASE}/mod_${MOD_NAME}_user_bfs.o \
							${T_BASE}/mod_${MOD_NAME}-LWIP \
							${T_BASE}/mod_${MOD_NAME}-LD_TIMESTAMP \
							${T_BASE}/mod_${MOD_NAME}-X86EMU_TIMESTAMP
	@$(call C_ECHO,LD $@)
	${V}$(call T_LD,${OBJFILES} \
		${T_BASE}/mod_${MOD_NAME}_user_bfs.o \
		${T_BASE}/libcommon_*.o \
		${T_BASE}/mod_${MOD_NAME}-LWIP*.o \
		${T_BASE}/mod_${MOD_NAME}-X86EMU*.o \
		$(shell cat ${T_BASE}/mod_${MOD_NAME}-LD_OBJS) \
		,$@,-N -r -T ${P_BASE}/modules/mod.ld)
